package org.dromara.web.plugins.file;


import cn.hutool.core.io.file.FileNameUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.file.FileUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.processing.Filer;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Component
public class LocalFileResolver implements InitializingBean {

    @Value("${localFile.folder}")
    private String localFolder;


    @Autowired
    PDFFileResolver pdfFileResolver;
    @Autowired
    TXTFileResolver txtFileResolver;
    @Autowired
    DOCFileResolver docFileResolver;

    private Map<String, FileResolver> resolverMap = new HashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {

        putResolver(pdfFileResolver);
        putResolver(txtFileResolver);
        putResolver(docFileResolver);
    }

    private void putResolver(FileResolver resolver) {
        String[] extend = resolver.supportedExtensions();
        for (String ext : extend) {
            resolverMap.put(ext.toLowerCase(), resolver);
        }
    }

    public String uploadFile(MultipartFile file, String fileName) {
        String fileId = UUID.randomUUID().toString().replaceAll("-", "") + "." + FileNameUtil.getSuffix(fileName);
        String filePath = localFolder + (localFolder.endsWith("/") ? "" : "/") + fileId;

        try {
            checkDir();
            IOUtils.copy(file.getInputStream(), new FileOutputStream(new File(filePath)));
        }catch ( Exception e) {
            e.printStackTrace();
        }

        return fileId;
    }



    public String resolveFileToText(String fileId) {
        String ext = FileNameUtil.getSuffix(fileId);
        FileResolver resolver = resolverMap.get(ext.toLowerCase());
        if (resolver == null) {
            return "";
        }

        return resolver.resolve(localFolder + (localFolder.endsWith("/") ? "" : "/") + fileId);
    }


    private void checkDir() {
        File file = new File(localFolder);
        if (!file.exists()) {
            file.mkdirs();
        }
    }
}
